package com.ruoyi.system.service.impl;

import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.StoreInDetailMapper;
import com.ruoyi.system.mapper.StoreInMapper;
import com.ruoyi.system.mapper.VendorSettlementMapper;
import com.ruoyi.system.service.IVendorSettlementService;
import com.ruoyi.system.service.RestaurantStoreResourceService;
import com.ruoyi.system.service.VendorService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author wlmes
 * @date 2023-12-17
 */
@Service
public class VendorSettlementServiceImpl implements IVendorSettlementService {
    @Resource
    private VendorSettlementMapper vendorSettlementMapper;

    @Resource
    VendorSettlementDetailServiceImpl vendorSettlementDetailService;

    @Resource
    VendorService vendorService;

    @Resource
    RestaurantStoreResourceService restaurantStoreResourceService;

    @Resource
    StoreInMapper storeInMapper;

    @Resource
    StoreInDetailMapper storeInDetailMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public VendorSettlement selectVendorSettlementById(Long id) {
        return vendorSettlementMapper.selectVendorSettlementById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param vendorSettlement 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<VendorSettlement> selectVendorSettlementList(VendorSettlement vendorSettlement) {
        return vendorSettlementMapper.selectVendorSettlementList(vendorSettlement);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param vendorSettlement 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertVendorSettlement(VendorSettlement vendorSettlement) {
        if (StringUtils.isNull(vendorSettlement)) {
            throw new BaseException("新增【请填写功能名称】失败！");
        }
        vendorSettlement.setCreateTime(DateUtils.getNowDate());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        vendorSettlement.setCreateBy(SecurityUtils.getNickName());
        vendorSettlement.setCreateTime(new Date());
        return vendorSettlementMapper.insertVendorSettlement(vendorSettlement);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param vendorSettlement 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateVendorSettlement(VendorSettlement vendorSettlement) {
        return vendorSettlementMapper.updateVendorSettlement(vendorSettlement);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteVendorSettlementByIds(Long[] ids) {
        if (StringUtils.isNull(ids)) {
            throw new BaseException("需要删除的【请填写功能名称】ID为空！");
        }
        return vendorSettlementMapper.deleteVendorSettlementByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteVendorSettlementById(Long id) {
        if (StringUtils.isNull(id)) {
            throw new BaseException("需要删除的【请填写功能名称】ID为空！");
        }
        return vendorSettlementMapper.deleteVendorSettlementById(id);
    }

    @Override
    @RepeatSubmit
    @Transactional(rollbackFor = Exception.class)
    public List<VendorSettlement> getNewSettlement(VendorSettlement query) {
        List<VendorSettlement> vendorSettlements = new ArrayList<>();
        //查询区域
        String area = "";
        if (query != null && StringUtils.isBlank(query.getArea())) {
            area = SecurityUtils.getUserLocation();
        }

        if (StringUtils.isBlank(area) || area.equals("全部")) {
            throw new BaseException("园区为空或全部的用户无法创建供应商结算单");
        }

        //计算核算日期
        //当前日期
        Date today = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //计算盘点账期
        //当前月 日
        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        int month = localDate.getMonthValue();
        int day = localDate.getDayOfMonth();
        String panDate = "";
        String panDateStart = "";
        String panDateEnd = "";

        if (StringUtils.isNotBlank(query.getSettlementTime())) {
            panDate = query.getSettlementTime() + "-25";
            int a = Integer.valueOf(panDate.split("-")[1]);
            if (a == 1) {
                panDateStart = (Integer.valueOf(panDate.split("-")[0]) - 1) + "-12-26" + " 00:00:00";
            } else {
                panDateStart = Integer.valueOf(panDate.split("-")[0]) + "-" + (Integer.valueOf(panDate.split("-")[1]) - 1) + "-26" + " 00:00:00";
            }
            panDateEnd = panDate + " 23:59:59";
        } else {
            if (day - 25 <= 0) {
                //本月25
                panDate = month + "月" + "25日";
            } else {
                //下月25
                panDate = month + 1 == 13 ? "1" : month + 1 + "月" + "25日";
            }

            if (month == 1) {
                panDateEnd = year + "-" + month + "-" + "25" + " 23:59:59";//先赋值在减

                year = year - 1;
                month = 12;
                panDateStart = year + "-" + month + "-" + "26" + " 00:00:00";
            } else {
                panDateEnd = year + "-" + month + "-" + "25" + " 23:59:59";//先赋值在减

                panDateStart = year + "-" + (month - 1) + "-" + "26" + " 00:00:00";
            }
        }

        //查询这个时间段所有的入库单-已确认的
        List<VendorSettlementSearch> outs = storeInDetailMapper.selectSettlementListByDate(panDateStart, panDateEnd);
        if (CollectionUtils.isEmpty(outs)) {
            throw new BaseException("未查询到当期任何供应商的已确认的入库单");
        }
        //按照供应商分组
        Map<Long, List<VendorSettlementSearch>> vendors = outs.stream().collect(Collectors.groupingBy(VendorSettlementSearch::getVendorId));
        String finalPanDate = panDate;
        String finalArea = area;
        vendors.forEach((k, v) -> {
            VendorSettlement vendorSettlement = new VendorSettlement();
            vendorSettlement.setVendorId(k);
            Vendor vendor = vendorService.selectById(vendorSettlement.getVendorId());
            if (vendor != null && StringUtils.isNotBlank(vendor.getName())) {
                vendorSettlement.setVendorName(vendor.getName());
            }
            vendorSettlement.setArea(finalArea);
            vendorSettlement.setBusinessNum(BaseController.createBusinessNum("VSD"));
            vendorSettlement.setSettlementTime(finalPanDate);
            vendorSettlement.setCreateBy(SecurityUtils.getNickName());
            vendorSettlement.setCreateTime(new Date());
            vendorSettlement.setStatus("0");
            //再以食材分组
            List<VendorSettlementDetail> details = new ArrayList<>();
            Map<Long, List<VendorSettlementSearch>> resources = v.stream().collect(Collectors.groupingBy(VendorSettlementSearch::getResourceId));
            resources.forEach((resourceId, s) -> {
                //加总 数量 金额 等
                VendorSettlementDetail vendorSettlementDetail = new VendorSettlementDetail();
                vendorSettlementDetail.setBusinessNum(vendorSettlement.getBusinessNum());
                vendorSettlementDetail.setVendorId(vendorSettlement.getVendorId());
                vendorSettlementDetail.setVendorName(vendorSettlement.getVendorName());
                vendorSettlementDetail.setResourceId(resourceId);
                RestaurantStoreResource storeResource = restaurantStoreResourceService.selectRestaurantStoreResourceById(vendorSettlementDetail.getResourceId());
                if (storeResource != null && StringUtils.isNotBlank(storeResource.getName())) {
                    vendorSettlementDetail.setResourceName(storeResource.getName());
                }
                //入库总金额
                BigDecimal inMoneyTotal = BigDecimal.ZERO;
                for (VendorSettlementSearch vendorSettlementSearch : s) {
                    inMoneyTotal = inMoneyTotal.add((vendorSettlementSearch.getAmount() == null ? BigDecimal.ZERO : vendorSettlementSearch.getAmount())
                            .multiply(vendorSettlementSearch.getPrice() == null ? BigDecimal.ZERO : vendorSettlementSearch.getPrice()));
                }
                vendorSettlementDetail.setInMoneyTotal(inMoneyTotal);

                //食材名称、入库数量合计、入库金额合计、结算单价（入库金额合计÷入库数量合计）、实际结算金额（入库数量合计 X 结算单价）、修改人、修改日期。
                vendorSettlementDetail.setInAmountTotal(s.stream().map(VendorSettlementSearch::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                vendorSettlementDetail.setSettlementPrice(vendorSettlementDetail.getInMoneyTotal().divide(vendorSettlementDetail.getInAmountTotal()));
                vendorSettlementDetail.setSettlementMoney(vendorSettlementDetail.getInAmountTotal().multiply(vendorSettlementDetail.getSettlementPrice()));

                details.add(vendorSettlementDetail);

                vendorSettlementDetailService.insertVendorSettlementDetail(vendorSettlementDetail);
            });

            vendorSettlement.setVendorSettlementDetailList(details);
            vendorSettlement.setMoney(details.stream().map(VendorSettlementDetail::getSettlementMoney).reduce(BigDecimal.ZERO, BigDecimal::add));
            vendorSettlements.add(vendorSettlement);

            //新增去重
            VendorSettlement settlement = new VendorSettlement();
            settlement.setSettlementTime(finalPanDate);
            settlement.setVendorId(k);
            List<VendorSettlement> settlements = vendorSettlementMapper.selectVendorSettlementList(settlement);
            if (!CollectionUtils.isEmpty(settlements)) {
//                throw new BaseException("该供应商" + vendorSettlement.getVendorName() + "在该结算日期" + finalPanDate + "已有结算单,请勿重复添加");
            } else {
                vendorSettlementMapper.insertVendorSettlement(vendorSettlement);
            }
        });

        return vendorSettlements;
    }
}
